package com.juyu.miliao.api.controller;

import com.juyu.miliao.api.cache.RobotMessageCache;
import com.juyu.miliao.api.domain.RobotMessage;
import com.juyu.miliao.api.rabbitMQ.RobotMessageMq;
import com.juyu.miliao.api.service.PackageOnlineService;
import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.domain.Subject;
import com.juyu.miliao.common.netease.NetEaseCloudUserService;
import com.juyu.miliao.common.util.VerifyUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 获取参数
 *
 * @author wbf
 */
@RestController
@RequestMapping("/missage")
public class MissageController {
    private final Logger logger = LoggerFactory.getLogger(MissageController.class);
    @Resource
    private PackageOnlineService packageOnlineService;

    @Autowired
    private RobotMessageMq robotMessageMq;
    /**
     * 机器人视频推送，拒绝接听发送文本
     */
    @GetMapping("/{userId:^[1-9][0-9]*$}/{robotId:^[1-9][0-9]*$}")
    public void getTextReply(HttpServletRequest request, @PathVariable("userId") long userId,
                             @PathVariable("robotId") long robotId) {
        CommonHead com = VerifyUtil.verifyCommonHead(request);
        int isOnline = packageOnlineService.getOnline(com);
        //随机获取要发送的内容
        List<RobotMessage> textReplyList = RobotMessageCache.INSTANCE.getRobotMessageList(5, isOnline);
        String test = textReplyList.get((int) (Math.random() * textReplyList.size())).getMessage();
        JSONObject body = new JSONObject();
        body.put("msg", test);
        //开发者扩展字段
        JSONObject ext = new JSONObject();
        try {
            String temp = NetEaseCloudUserService.getSendMsg(userId, robotId, 0, body.toString(), ext.toString(), "");
            if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200"))
                logger.error("发送普通消息异常-云信：userId={},message={}", userId, temp);
        } catch (Exception e) {
            logger.error("发送普通消息异常：userId={},error={}", userId, e);

        }
    }

    /**
     * 线下机器人聊天自动回复一句话
     */
    @GetMapping("/robot/{userId:^[1-9][0-9]*$}/{robotId:^[1-9][0-9]*$}")
    public void getRobotReply(HttpServletRequest request, @PathVariable("userId") long userId,
                              @PathVariable("robotId") long robotId) {
        CommonHead com = VerifyUtil.verifyCommonHead(request);
        int isOnline = packageOnlineService.getOnline(com);
        //随机获取要发送的内容
        List<RobotMessage> textReplyList = RobotMessageCache.INSTANCE.getRobotMessageList(6, isOnline);
        if(textReplyList==null || textReplyList.size()==0){
            logger.error("线下机器人聊天自动回复一句话-异常textReplyList空：userId={},message={},isOnline{}",
                    userId, com.toString() ,isOnline);
            return;
        }
        String test = textReplyList.get((int) (Math.random() * textReplyList.size())).getMessage();
        JSONObject body = new JSONObject();
        body.put("msg", test);
        //开发者扩展字段
        JSONObject ext = new JSONObject();
        try {
            String temp = NetEaseCloudUserService.getSendMsg(userId, robotId, 0, body.toString(), ext.toString(), "");
            if (!temp.substring(temp.indexOf("code") + 6, temp.indexOf("code") + 9).equals("200")){
                    logger.error("发送普通消息异常-云信：userId={},message={}", userId, temp);
            }
        } catch (Exception e) {
                logger.error("发送普通消息异常：userId={},error={}", userId, e);
        }
    }

    /**
     * 1-登录机器人  2-注册机器人
     * 机器人停止发送消息
     * @param robotType
     */
    @GetMapping("/robot/stop/{robotType}/{sendUserId}")
    public void stopRobotMessage(@PathVariable("robotType") Integer robotType,@PathVariable("sendUserId") Long sendUserId,
                                 Authentication token){
        Subject subject = (Subject) token.getPrincipal();
        JSONObject json = new JSONObject();
        json.put("robotType",robotType);
        json.put("userId",subject.getId());
        json.put("sendUserId",sendUserId);
        robotMessageMq.stopRobotMessageMq(json.toString());
    }

}